import os
import sys

students = []


def menu():
    """显示主菜单并获取用户选择"""
    print('''
    +----------------------+
    |   1. 录入学生信息     |
    |   2. 显示所有学生     |
    |   3. 查询学生信息     |
    |   4. 删除学生信息     |
    |   5. 保存到文件       |
    |   0. 退出系统         |
    +----------------------+''')
    while True:
        try:
            choice = int(input('请输入您的选择(0-5): '))
            if 0 <= choice <= 5:
                return choice
            print("输入错误，请输入0-5之间的数字！")
        except ValueError:
            print("请输入有效的数字！")


def insert():
    """添加学生信息"""
    print("\n[新增学生信息]")
    while True:
        student_id = input('请输入学号(输入q退出): ')
        if student_id.lower() == 'q':
            return

        # 检查学号是否已存在
        if any(s['学号'] == student_id for s in students):
            print("该学号已存在，请重新输入！")
            continue

        name = input('请输入姓名: ')

        while True:
            try:
                age = int(input('请输入年龄: '))
                if 10 <= age <= 100:  # 合理年龄范围检查
                    break
                print("年龄应在10-100岁之间！")
            except ValueError:
                print("请输入有效的数字年龄！")

        gender = ''
        while gender not in ('男', '女'):
            gender = input('请输入性别(男/女): ')
            if gender not in ('男', '女'):
                print('请输入正确的性别！')

        class_name = input('请输入班级: ')

        students.append({
            '学号': student_id,
            '姓名': name,
            '年龄': age,
            '性别': gender,
            '班级': class_name
        })
        print(f'[成功] 已添加学生: {name}')
        save()  # 每次添加后自动保存
        break


def show():
    """显示所有学生信息"""
    print("\n[所有学生信息]")
    if not students:
        print("当前没有学生记录！")
        return

    # 使用str.format进行对齐（兼容中英文混排）
    header = "{:<10}{:<10}{:<6}{:<6}{:<10}".format(
        "学号", "姓名", "年龄", "性别", "班级"
    )
    print("-" * len(header))
    print(header)
    print("-" * len(header))

    for student in students:
        row = "{:<10}{:<10}{:<6}{:<6}{:<10}".format(
            student['学号'],
            student['姓名'],
            student['年龄'],
            student['性别'],
            student['班级']
        )
        print(row)
    print("-" * len(header))
    print(f"共 {len(students)} 条记录")


def search():
    """查询学生信息"""
    print("\n[查询学生信息]")
    if not students:
        print("当前没有学生记录！")
        return

    keyword = input('请输入学号或姓名: ').strip()
    results = [
        s for s in students
        if keyword in (s['学号'], s['姓名'])
    ]

    if not results:
        print("未找到匹配的学生！")
        return

    print("\n查询结果:")
    print("-" * 50)
    print(f"{'学号':<10}{'姓名':<8}{'年龄':<6}{'性别':<6}{'班级':<10}")
    print("-" * 50)
    for s in results:
        print(f"{s['学号']:<10}{s['姓名']:<8}{s['年龄']:<6}{s['性别']:<6}{s['班级']:<10}")
    print("-" * 50)


def delete():
    """删除学生信息"""
    print("\n[删除学生信息]")
    if not students:
        print("当前没有学生记录！")
        return

    student_id = input('请输入要删除的学号: ')
    for i, s in enumerate(students):
        if s['学号'] == student_id:
            students.pop(i)
            print(f"已删除学号为 {student_id} 的学生")
            save()  # 删除后自动保存
            return
    print("未找到该学号的学生！")


def save():
    """保存数据到文件"""
    try:
        with open('students.txt', 'w', encoding='utf-8') as f:
            for s in students:
                f.write(f"{s['学号']},{s['姓名']},{s['年龄']},{s['性别']},{s['班级']}\n")
        print("[自动保存] 数据已保存！")
    except Exception as e:
        print(f"保存失败: {str(e)}")


def load():
    """从文件加载数据"""
    if not os.path.exists('students.txt'):
        return

    try:
        with open('students.txt', 'r', encoding='utf-8') as f:
            for line in f:
                line = line.strip()
                if not line:
                    continue

                parts = line.split(',')
                if len(parts) != 5:
                    continue

                students.append({
                    '学号': parts[0],
                    '姓名': parts[1],
                    '年龄': int(parts[2]),
                    '性别': parts[3],
                    '班级': parts[4]
                })
        print("[系统] 已从文件加载学生数据")
    except Exception as e:
        print(f"加载数据失败: {str(e)}")


def main():
    """主程序"""
    load()  # 启动时加载数据

    print('\n' + '=' * 50)
    print(' ' * 15 + '学生管理系统')
    print('=' * 50)

    while True:
        choice = menu()

        if choice == 0:
            print("\n感谢使用学生管理系统，再见！")
            sys.exit()
        elif choice == 1:
            insert()
        elif choice == 2:
            show()
        elif choice == 3:
            search()
        elif choice == 4:
            delete()
        elif choice == 5:
            save()
        else:
            print("无效选择，请重新输入！")


if __name__ == '__main__':
    main()